﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Net.Http;
using System.Net.Http.Headers;
using TPLOAWebClient.Resources;
using System.Web.Security;

namespace TPLOAWebClient
{
    public partial class staffsubmitloa : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (monthtoDdl.SelectedValue == "0")
            {
                CustomValidator2.IsValid = false;
            }
            else
            {
                CustomValidator2.IsValid = true;
            }
            if (monthfromDdl.SelectedValue == "0")
            {
                CustomValidator1.IsValid = false;
            }
            else
            {
                CustomValidator1.IsValid = true;
            }
            HttpClient client = (HttpClient)Session["httpclient"];
            HttpResponseMessage response = null;

            if (Session["username"] != null)
            {
                response = client.GetAsync("api/members/" + Session["username"]).Result;
                var member = response.Content.ReadAsAsync<Member>().Result;
                if (member.UserType.Equals("Student"))
                {
                    Response.Redirect("studentprofile.aspx");
                }
                else if (member.UserType.Equals("Clinic"))
                {
                    Response.Redirect("clinicprofile.aspx");
                }
                else if (member.UserType.Equals("Admin"))
                {
                    Response.Redirect("adminprofile.aspx");
                }

                response = client.GetAsync("api/Staffs/" + Session["username"]).Result;
                var staff = response.Content.ReadAsAsync<Staff>().Result;
                if (!staff.ApprovePermissions)
                {
                    viewloaBtn.Visible = false;
                }
                else
                {
                    viewloaBtn.Visible = true;
                }
            }

            if (!IsPostBack)
            {
                dateInit();
                timeInit();


                response = client.GetAsync("api/Students").Result;  // Blocking call!
                {
                    if (response.IsSuccessStatusCode)
                    {
                        // Parse the response body. Blocking!
                        ArrayList array = new ArrayList();
                        var student = response.Content.ReadAsAsync<IEnumerable<Student>>().Result;
                        if (student != null)
                        {
                            foreach (var s in student)
                            {
                                array.Add(s.AdminNo);
                            }
                            DropDownList1.DataSource = array;
                            DropDownList1.DataBind();
                        }

                    }
                }
            }
        }

        protected void timeInit()
        {
            string time = "";

            for (int i = 0; i < 24; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    if (j == 0)
                    {
                        time = i.ToString().PadLeft(2, '0') + ":00:00";
                    }
                    else
                    {
                        time = i.ToString().PadLeft(2, '0') + ":30:00";
                    }
                    timefromDdl.Items.Add(time);
                    timetoDdl.Items.Add(time);
                }
            }
        }

        protected void dateInit()
        {
            int thisYear = DateTime.Today.Year;

            for (int m = 1; m <= 12; m++)
            {
                monthfromDdl.Items.Add(m.ToString());
                monthtoDdl.Items.Add(m.ToString());
            }

            for (int y = thisYear; y <= thisYear + 1; y++)
            {
                yearfromDdl.Items.Add(y.ToString());
                yeartoDdl.Items.Add(y.ToString());
            }
        }

        protected void monthfromDdl_SelectedIndexChanged(object sender, EventArgs e)
        {
            int monthNo;
            int dayNo = 0;

            if (monthfromDdl.SelectedItem.Text != "Month")
            {
                dayfromDdl.Enabled = true;
                yearfromDdl.Enabled = true;

                if (dayfromDdl.SelectedIndex > 1)
                {
                    dayNo = Convert.ToInt32(dayfromDdl.SelectedItem.Text);
                }

                dayfromDdl.Items.Clear();
                dayfromDdl.Items.Add("Day");

                monthNo = monthfromDdl.SelectedIndex;

                for (int d = 1; d <= 31; d++)
                {
                    dayfromDdl.Items.Add(d.ToString());
                    if (monthNo == 2 && d == 29)
                    {
                        break;
                    }
                    else if ((monthNo == 4 || monthNo == 6 || monthNo == 9 || monthNo == 11) && d == 30)
                    {
                        break;
                    }
                }

                if (dayfromDdl.Items.Count - 1 >= dayNo)
                {
                    dayfromDdl.SelectedIndex = dayNo;
                }
            }
            else if (monthfromDdl.SelectedItem.Text == "Month")
            {
                dayfromDdl.SelectedIndex = 0;
                yearfromDdl.SelectedIndex = 0;
                dayfromDdl.Enabled = false;
                yearfromDdl.Enabled = false;
            }

        }

        protected void monthtoDdl_SelectedIndexChanged(object sender, EventArgs e)
        {
            int monthNo;
            int dayNo = 0;

            if (monthtoDdl.SelectedItem.Text != "Month")
            {
                daytoDdl.Enabled = true;
                yeartoDdl.Enabled = true;

                if (daytoDdl.SelectedIndex > 1)
                {
                    dayNo = Convert.ToInt32(daytoDdl.SelectedItem.Text);
                }

                daytoDdl.Items.Clear();
                daytoDdl.Items.Add("Day");

                monthNo = monthtoDdl.SelectedIndex;

                for (int d = 1; d <= 31; d++)
                {
                    daytoDdl.Items.Add(d.ToString());
                    if (monthNo == 2 && d == 29)
                    {
                        break;
                    }
                    else if ((monthNo == 4 || monthNo == 6 || monthNo == 9 || monthNo == 11) && d == 30)
                    {
                        break;
                    }
                }

                if (daytoDdl.Items.Count - 1 >= dayNo)
                {
                    daytoDdl.SelectedIndex = dayNo;
                }
            }
            else if (monthtoDdl.SelectedItem.Text == "Month")
            {
                daytoDdl.SelectedIndex = 0;
                yeartoDdl.SelectedIndex = 0;
                daytoDdl.Enabled = false;
                yeartoDdl.Enabled = false;
            }
        }

        protected void gradedassignmentRbl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (gradedassignmentRbl.SelectedValue == "Yes")
            {
                gradedassignmentTbx.Visible = true; 
                RequiredFieldValidator2.Enabled = true;
                gradedassignmentTbx.Text = "";
                Panel1.Visible = true;
            }
            else
            {
                gradedassignmentTbx.Visible = false; 
                RequiredFieldValidator2.Enabled = false;
                Panel1.Visible = false;
            }
        }

        protected void submitBtn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (!(monthfromDdl.SelectedIndex == 0 || dayfromDdl.SelectedIndex == 0 || yearfromDdl.SelectedIndex == 0) &&
                    !(monthtoDdl.SelectedIndex == 0 || daytoDdl.SelectedIndex == 0 || yeartoDdl.SelectedIndex == 0))
                {
                    string fromDate = yearfromDdl.SelectedItem.Text.PadLeft(4, '0') +
                        monthfromDdl.SelectedItem.Text.PadLeft(2, '0') +
                        dayfromDdl.SelectedItem.Text.PadLeft(2, '0');
                    string toDate = yeartoDdl.SelectedItem.Text.PadLeft(4, '0') +
                        monthtoDdl.SelectedItem.Text.PadLeft(2, '0') +
                        daytoDdl.SelectedItem.Text.PadLeft(2, '0');
                    string todayDate = string.Format("{0:0000}", DateTime.Now.Year.ToString()) +
                        string.Format("{0:00}", DateTime.Now.Month.ToString()) +
                        string.Format("{0:00}", DateTime.Now.Day.ToString());

                    bool clash = false;
                    if (gradedassignmentRbl.SelectedValue == "Yes")
                    {
                        clash = true;
                    }

                    if ((Convert.ToInt32(toDate) - Convert.ToInt32(fromDate) >= 0) &&
                        (Convert.ToInt32(fromDate) - Convert.ToInt32(todayDate) >= 14))
                    {
                        HttpClient client = (HttpClient)Session["httpclient"];

                        var Loa = new LOA()
                        {
                            Type = "LOA",
                            SubmitDateTime = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() +
                            " " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString(),
                            StartDateTime = yearfromDdl.SelectedValue + "-" + monthfromDdl.SelectedValue + "-" + dayfromDdl.SelectedValue + " " + timefromDdl.SelectedValue,
                            EndDateTime = yeartoDdl.SelectedValue + "-" + monthtoDdl.SelectedValue + "-" + daytoDdl.SelectedValue + " " + timetoDdl.SelectedValue,
                            LOAReason = reasonTbx.Text,
                            GradedAssignmentClash = clash,
                            GradedAssignmentClashDetails = gradedassignmentTbx.Text,
                            ReviewStatus = "Pending",
                            StudentAdminNo = DropDownList1.SelectedValue
                        };

                        HttpResponseMessage response = client.PostAsJsonAsync("api/LOAs", Loa).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            resultLbl.Visible = true;
                            resultLbl.Text = "LOA successfully is created at "+DateTime.Now.ToLongDateString()+" "+DateTime.Now.ToLongTimeString();

                        }
                        else
                        {
                            resultLbl.Visible = true;
                            resultLbl.Text = "LOA cannot be created.";
                        }
                    }
                    else
                    {
                        resultLbl.Text = "LOA must be submitted at least 14 days before the commencement date & 'From' date must be earlier than 'End' date";
                    }
                }
            }
        }


        protected void profileBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("staffprofile.aspx");
        }

        protected void viewloaBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("staffviewloa.aspx");
        }

        protected void submitloaBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("staffsubmitloa.aspx");
        }

        protected void faqBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("stafffaq.aspx");
        }

        protected void otherservicesBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("staffotherservice.aspx");
        }

        protected void LogoutBtn_Click(object sender, EventArgs e)
        {
            Session.Abandon();
            FormsAuthentication.SignOut();
            Response.Redirect("default.aspx");
        }



    }
}
